package com.example.demo.filter;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.Message;
import com.example.demo.entity.User;
import com.example.demo.entity.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Component
public class VerifyFilter extends GenericFilterBean {
    private String FilterUrl = "/api/auth/login";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String code=request.getParameter("code");
        //String verify = (String) request.getSession().getAttribute("index_code");
       // User user1 = BeanUtil.fillBeanWithMap(entries, new User(), false);
        String verify=stringRedisTemplate.opsForValue().get("index_code");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "text/html;charset=utf-8");
            if (FilterUrl.equals(request.getServletPath())) {
                if (code != null && !"".equals(code)&&verify != null && !"".equals(verify)){
                    if (!verify.equalsIgnoreCase(code)) {
                        response.getWriter().write(JSONObject.toJSONString(Message.failure(400, "code is error")));
                    } else chain.doFilter(request, response);
            }else response.getWriter().write(JSONObject.toJSONString(Message.failure(400, "code is null")));
            } else chain.doFilter(request, response);
    }
}
